package com.fenghongzhang.kotlin1903.fragment

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.fenghongzhang.kotlin1903.mvp.adapter.FoodAdapter

import com.fenghongzhang.kotlin1903.R
import com.fenghongzhang.kotlin1903.api.FoodApi
import com.fenghongzhang.kotlin1903.model.Data
import com.fenghongzhang.kotlin1903.model.Food
import com.fenghongzhang.kotlin1903.plus.toast
import com.fenghongzhang.kotlin1903.util.RetrofitManager
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_home.*

/**
 * A simple [Fragment] subclass.
 */
class HomeFragment : Fragment() {

    private lateinit var foodAdapter: FoodAdapter
    private  lateinit  var list : MutableList<Data>
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        home_btn.setOnClickListener{
//            Toast.makeText(activity,"内容",Toast.LENGTH_SHORT).show()
            "内容".toast()
        }

        list = mutableListOf()

//        var list1  = ArrayList<Data>()
//        list1.add(Data("1","2","3","4","5",6))
//        list.add(0,Data("1","2","3","4","5",6))
//        list.add(1,Data("1","2","3","4","5",6))
//        list.add(2,Data("1","2","3","4","5",6))
//        list.add(3,Data("1","2","3","4","5",6))

        rv.layoutManager = LinearLayoutManager(activity)
        foodAdapter = activity?.let { FoodAdapter(it,list) }!!
        rv.adapter = foodAdapter

        RetrofitManager.getRetrofit().create(FoodApi::class.java)
            .getFood()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(object : Observer<Food>{
                override fun onSubscribe(d: Disposable) {
                    Log.i("http","订阅了")
                }

                override fun onNext(t: Food) {
                    Log.i("http",t.toString())
                    list.clear()
                    list.addAll(t.data)
                }

                override fun onError(e: Throwable) {
                }

                override fun onComplete() {
                }

            })

        request_food.setOnClickListener{
                foodAdapter.notifyDataSetChanged()
        }
    }

}
